package net.pa.ovpn.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.pa.ovpn.constant.ovpnConstant;
import net.pa.ovpn.model.FileObject;
import net.pa.ovpn.utils.FileUtil;
import net.pa.ovpn.utils.ovpnUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);		
		
		String formattedDate = getLocaleDate(locale);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping(value="/sendRequest")
	public @ResponseBody String getRequest(Locale locale){
		return getLocaleDate(locale);
	}
	
	private String getLocaleDate(Locale locale){
		Date date = new Date();
//		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);		
//		String formattedDate = dateFormat.format(date);
		String formattedDate = date.toString();
		return formattedDate;
	}
	
	@RequestMapping(value = "/certificate")
	public String toCertificateCenter(Model model){
		List<FileObject> fileList = null;;
		try {
			fileList = getFiles(getFiles());
			FileUtil.createFileRecord(getFileDir(), fileList);
		} catch (Exception e) {
			logger.error(e.getMessage());
			fileList = new ArrayList<FileObject>();
		}
		model.addAttribute("fileList", fileList);
		return "certificate";
	}
	
	@RequestMapping(value = "/certificate/download/{id}")
	public void download(@PathVariable("id") String id,	HttpServletRequest request, HttpServletResponse response) {

		try {
			this.download(id, response);
		} catch (Exception e) {
			if (e.getClass().getSimpleName().indexOf("ClientAbortException") != -1) {
				logger.info("Client abort download, file id=" + id);
			} else {
				e.printStackTrace();
				logger.debug(e.getMessage());
			}
		}

	}

	private void download(String id, HttpServletResponse response) throws Exception {

		File file = getFileById(id);

		InputStream input = null;
		try {
			input = new FileInputStream(file);
			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[1024];
			int length;
			while ((length = input.read(b)) > 0) {
				os.write(b, 0, length);
			}
		} finally {
			if (null != input) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private List<FileObject> getFiles(List<FileObject> fileList) throws Exception {		
		List<FileObject> fromXML = FileUtil.readFileRecord(getFileDir());
		for (FileObject fo : fileList) {
			FileObject temp = getFileObject(fo.getName(), fo.getPath(), fromXML);
			if (temp != null) {
				if (temp.getId() == null) {
					temp.setId(UUID.randomUUID().toString());
				}
				fo.setId(temp.getId());
			} else {
				fo.setId(UUID.randomUUID().toString());
			}
			String operation = String.format(ovpnConstant.operationFormat, fo.getId(),"Download");
			fo.setOperation(operation);
		}
		return fileList;
	}
	
	private List<FileObject> getFiles() throws Exception{
		List<FileObject> fileList = new ArrayList<FileObject>();
		List<File> files = FileUtil.getFilelist(getFileDir());
		for (File file : files) {
			FileObject fo = new FileObject();
			fo.setName(file.getName());
			fo.setPath(file.getAbsolutePath());			
			fileList.add(fo);
		}
		return fileList;
	}
	
	private FileObject getFileObject(String name, String path, List<FileObject> fileList) {
		for (FileObject fileObject : fileList) {
			if (fileObject.getName().equals(name) && fileObject.getPath().equals(path)) {
				return fileObject;
			}
		}
		return null;
	}
	
	
	@SuppressWarnings("unused")
	private File getFile(String fileName) throws Exception{
		List<File> files = FileUtil.getFilelist(getFileDir());
		for (File file : files) {
			if(file.getName().equals(fileName)){
				return file;
			}
		}
		return null;
	}
	
	private File getFileById(String id) throws Exception{
		List<FileObject> fromXML = FileUtil.readFileRecord(getFileDir());
		for (FileObject fo : fromXML) {
			if(fo.getId().equals(id)){
				return new File(fo.getPath());
			}
		}
		return null;
	}
	
	private String getFileDir() throws Exception{
		return ovpnUtil.getProperty(ovpnConstant.property_downloadPath);
	}	
		
}
